//
//  ClubLeaderManagerVC.m
//  SelfDrivingTravelling-IOS
//
//  Created by Teplot_01 on 16/8/20.
//  Copyright © 2016年 Teplot_01. All rights reserved.
//

#import "ClubLeaderManagerVC.h"
#import "ClubManagerCell.h"
#import "AddLaederManagerVC.h"
@interface ClubLeaderManagerVC ()<UITableViewDelegate,UITableViewDataSource>

@end

@implementation ClubLeaderManagerVC
{
    UITableView *_tableView;
    NSMutableArray *rowCountArr;

    NSMutableArray *_selArr;//选中的行数添加到数组中，
    
    BOOL isBest;
    NSString *_str;
//    int index;//选中的行数
//    NSMutableArray *_deleteArr;
//    int indexDelete;//
//    NSIndexPath *path;
    
    //请求下来的字典
    NSDictionary *_responseDic;
    //请求下来的数组
    NSMutableArray *_responseArr;
}
- (void)viewWillAppear:(BOOL)animated{
    [self requsetForLeaderMan];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = White_Color;
    self.title = @"领队管理";
    
//    [self requsetForLeaderMan];
    [self initTableViewWithManager];
    isBest = YES;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"clublingduiguanli"] style:UIBarButtonItemStylePlain target:self action:@selector(tianjiaAction)];
    
    _selArr = [[NSMutableArray alloc]init];
    //设置多余的分割线不显示
     _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
//    rowCount = 10;
    rowCountArr = [NSMutableArray array];
    for (int i = 0; i < 5; i++) {
        [rowCountArr addObject:[NSString stringWithFormat:@"%d",i]];
    }
}
- (void)requsetForLeaderMan{
    //参数
    NSDictionary *parameters = @{
                                 @"clubId":[NSString readToNSDefaultsWithKey:kClubId],
                                 @"pageNum": @"1",
                                 @"pageSize": @"10",
                                 };
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/club/LeadList.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD showWithStatus:@"请求中"];
        _responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@>>>>",_responseDic);

        _responseArr = [[NSMutableArray alloc]init];
        [_responseArr addObjectsFromArray:_responseDic[@"list"]];
        NSString *error = _responseDic[@"code"];
        if (![_responseDic[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
        }else{
            //创建成功
//            [SVProgressHUD showSuccessWithStatus:@"请求领队列表成功"];
            [SVProgressHUD dismiss];
            [_tableView reloadData];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:@"请求失败"];
    }];
}
- (void)initTableViewWithManager{
    _tableView = [[UITableView alloc]initWithFrame:self.view.frame];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
}
#pragma - mrak UITabelViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _responseArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ClubManagerCell *cell = [[NSBundle mainBundle]loadNibNamed:@"ClubManagerCell" owner:nil options:nil][0];
    cell.managerName.text = _responseDic[@"list"][indexPath.row][@"realName"];
    cell.managerPhone.text = _responseDic[@"list"][indexPath.row][@"phone"];
    cell.tag = indexPath.row;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (isBest == YES) {
        cell.bestIcon.image = [UIImage imageNamed:@"优秀领队icon"];
    }else{
        cell.bestIcon.image = [UIImage imageNamed:@"l"];
    }
    
    //1.默认是优秀，(默认显示“取消优秀”) 有一个数组，存放非优秀的，数组中没有时就是优秀，设置为非优秀时加入数组，然后判断数组是否含有，更改是否优秀
    //2.请求下来数据之后，把非优秀的先存放到数组中
    if ([_selArr containsObject:@(indexPath.row)]){

    }else{

    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}
#pragma - mark 滑动手势删除某一行时出现多个按钮 适用iOS8及之后系统
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    //添加一个删除按钮
    UITableViewRowAction *deleteBtn = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction *action,NSIndexPath *indexPath){
        //删除领队
        //先把需要删除的领队Id上传服务器
        NSString *idStr = _responseDic[@"list"][indexPath.row][@"id"];
        NSDictionary *parameters = @{
                                     
                                     @"id": idStr,
                                     
                                     };
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer=[AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        [manager POST:@"http://115.28.152.130/tour/v1/club/deleteLead.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
            NSDictionary *_responseDicForLed = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"%@>>>>",_responseDicForLed);
//            _responseArr = _responseDicForLed[@"list"];
            NSString *error = _responseDicForLed[@"code"];
            if (![_responseDicForLed[@"code"] isEqualToString:@"0000"]) {
                [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
            }else{
                [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                //删除请求成功后，再次请求新的数据
                [self requsetForLeaderMan];
            }
            
        } failure:^(NSURLSessionDataTask *operation, NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"删除领队失败"];
        }];
        
    }];
    if (isBest == NO) {
        _str = @"设为优秀";
    }else{
        _str = @"取消优秀";
    }
    //添加一个是否置优秀按钮
    UITableViewRowAction *bestBtn = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:_str handler:^(UITableViewRowAction *action,NSIndexPath *indexPath){
        //
        if (isBest == YES) {
            isBest = NO;
            [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }else{
            isBest = YES;
            [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }
        
    }];
    bestBtn.backgroundColor = Orange_Color;
    return @[deleteBtn,bestBtn];
}
- (void)tianjiaAction{
    NSString *str = [NSString readToNSDefaultsWithKey:kStatus];
    if ([str isEqualToString:@"2"]) {
        AddLaederManagerVC *vc = [[AddLaederManagerVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [SVProgressHUD showInfoWithStatus:@"俱乐部没有通过审核，请稍后再试"];
    }
    
}
//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return UITableViewCellEditingStyleDelete;
//}
//-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (editingStyle==UITableViewCellEditingStyleDelete) {
//        //先删除数据源里面对应的数据
//        [rowCountArr removeObjectAtIndex:indexDelete];
//        //再删除UI
//        [_tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]  withRowAnimation:UITableViewRowAnimationFade];
//        [_tableView reloadData];
//    }
//}

////Btn点击事件
//- (void)bestBtnAction:(UIButton *)sender{
//    index = (int)sender.tag - 100;
////    NSLog(@"---当前选中的是cell的第%d行---",index);
//    [_selArr addObject:@(index)];
//    UIButton *bestBtn = (UIButton *)sender;
//    [bestBtn setTitle:@"设为优秀" forState:UIControlStateNormal];
//    [bestBtn addTarget:self action:@selector(cancelBtnAction:) forControlEvents:UIControlEventTouchUpInside];
//}
//- (void)cancelBtnAction:(UIButton *)sender{
//    index = (int)sender.tag - 100;
//    [_selArr removeObject:@(index)];
//    UIButton *cancelBestBtn = (UIButton *)sender;
//    [cancelBestBtn setTitle:@"取消优秀" forState:UIControlStateNormal];
//    [cancelBestBtn addTarget:self action:@selector(bestBtnAction:) forControlEvents:UIControlEventTouchUpInside];
//}
//- (void)deleteBtnAction:(UIButton *)sender{
//    //删除的操作
//    [_tableView setEditing:!_tableView.isEditing animated:YES];
//    [_tableView reloadData];
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
